//
//  yxpPulldownList.m
//  TestProject
//
//  Created by 杨小平 on 14-8-26.
//  Copyright (c) 2014年 yangxiaoping. All rights reserved.
//

#import "yxpPulldownList.h"

#define DEGREES_TO_RADIANS(angle) ((angle)/180.0 *M_PI)  //将角度转为弧度
#define RADIANS_TO_DEGREES(radians) ((radians)*(180.0/M_PI)) //将弧度转为角度

#define DROPDOWN_VIEW_MAX_HEIGHT 240.0f  //下拉列表的最高下拉高度
#define DROPDOWN_TABLECELL_HEIGHT 40.0f  //下拉列表行高度
#define DROPDOWN_mTableBaseView_BOTTOM_HEIGHT 30.0f //下拉列表底部点击按钮高度

@interface yxpPulldownList ()

@end

@implementation yxpPulldownList

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame dataSource:(id)datasource delegate:(id) delegate superView:(UIView *)superView
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.mSuperView=superView;
        [superView addSubview:self];
        
        //设置背景颜色
        //self.image=[UIImage imageNamed:@"buttonBg"];
        self.userInteractionEnabled=YES;
        
        //当前默认展开的分组
        currentExtendSection = -1;
        currentSelectIndex=0;
        currentSelectTitleIndex=0;
        
        //实现数据和结构委托
        self.dataSource = datasource;
        self.delegate = delegate;
        
        //代理返回有多少列
        NSInteger sectionNum =0;
        if ([self.dataSource respondsToSelector:@selector(numberOfSections)] ) {
            sectionNum = [self.dataSource numberOfSections];
        }
        if (sectionNum == 0) {
            self = nil;
        }
        
        //初始化默认显示view
        
        //每列的宽度
        CGFloat sectionWidth = (1.0*(frame.size.width)/sectionNum);
        
        for (int i = 0; i <sectionNum; i++) {
            //创建每列表头按钮
            UIButton *sectionBtn = [[UIButton alloc] initWithFrame:CGRectMake(sectionWidth*i, 1, sectionWidth, frame.size.height-2)];
            sectionBtn.tag = SECTION_BTN_TAG_BEGIN + i;
            [sectionBtn addTarget:self action:@selector(sectionBtnTouch:) forControlEvents:UIControlEventTouchUpInside];
            
            //设置每行显示的文字
            sectionBtnTitle= @"--";
            if ([self.dataSource respondsToSelector:@selector(titleInSection:index:titleIndex:)]) {
                
                //返回每列默认选中的行数
                currentSelectIndex=[self.dataSource defaultShowSection:i];
                currentSelectTitleIndex=[self.dataSource defaultShowSection:i index:currentSelectIndex];
                sectionBtnTitle=[self.dataSource titleInSection:i index:currentSelectIndex titleIndex:currentSelectTitleIndex];
            }
            
            [sectionBtn  setTitle:sectionBtnTitle forState:UIControlStateNormal];
            [sectionBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            sectionBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14.0f];
            [self addSubview:sectionBtn];
            
            //创建图标
            UIImageView *sectionBtnIv = [[UIImageView alloc] initWithFrame:CGRectMake(sectionWidth*i +(sectionWidth - 16), (self.frame.size.height-12)/2, 12, 12)];
            [sectionBtnIv setImage:[UIImage imageNamed:@"down_dark.png"]];
            [sectionBtnIv setContentMode:UIViewContentModeScaleToFill];
            sectionBtnIv.tag = SECTION_IV_TAG_BEGIN + i;
            
            [self addSubview: sectionBtnIv];
            
            //给两列之间创建一个分割线
            if (i<sectionNum && i != 0) {
                UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(sectionWidth*i, frame.size.height/4, 1, frame.size.height/2)];
                lineView.backgroundColor = [UIColor lightGrayColor];
                [self addSubview:lineView];
            }
            
        }
        
    }
    return self;
}

-(void)sectionBtnTouch:(UIButton *)btn
{
    //得到点击的列数的tag值
    NSInteger section = btn.tag - SECTION_BTN_TAG_BEGIN;
    
    UIImageView *currentIV= (UIImageView *)[self viewWithTag:(SECTION_IV_TAG_BEGIN +section)];
    
    [UIView animateWithDuration:0.3 animations:^{
        currentIV.transform = CGAffineTransformRotate(currentIV.transform, DEGREES_TO_RADIANS(180));
    }];
    
    //判断是否是当前列
    if (currentExtendSection == section) {
        [self hideExtendedChooseView];
    }else{
        currentExtendSection = section;
        currentIV = (UIImageView *)[self viewWithTag:SECTION_IV_TAG_BEGIN + section];
        
        
        [UIView animateWithDuration:0.1 animations:^{
            currentIV.transform = CGAffineTransformRotate(currentIV.transform, DEGREES_TO_RADIANS(180));
        }];
        
        NSInteger defaultIndex=[self.dataSource defaultShowSection:currentExtendSection];
        NSInteger defaultTitleIndex=[self.dataSource defaultShowSection:currentExtendSection index:defaultIndex];
        
        [self showChooseListViewInSection:currentExtendSection choosedIndex:defaultIndex andTitleIndex:defaultTitleIndex];
        
    }
}
-(void)showChooseListViewInSection:(NSInteger)section choosedIndex:(NSInteger)index andTitleIndex:(NSInteger)titleIndex
{
    //单元列的宽度
    //int sectionWidth = (self.frame.size.width)/[self.dropDownDataSource numberOfSections];
    int sectionWidth=self.frame.size.width/2.0;
    
    NSInteger numberRows=[self.dataSource numberOfRowsInSection:section];
    //计算高度
    currentSectionHeight=(numberRows*DROPDOWN_TABLECELL_HEIGHT+DROPDOWN_mTableBaseView_BOTTOM_HEIGHT)>DROPDOWN_VIEW_MAX_HEIGHT?DROPDOWN_VIEW_MAX_HEIGHT:(numberRows*DROPDOWN_TABLECELL_HEIGHT+DROPDOWN_mTableBaseView_BOTTOM_HEIGHT);
    
    if (!self.mTableView) {
        
        //创建一个表格父视图 按钮一下的部分
        //self.mSuperView.frame.size.height - self.frame.origin.y - self.frame.size.height
        self.mTableBaseView = [[UIView alloc] initWithFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y + self.frame.size.height , self.frame.size.width,self.mSuperView.frame.size.height-self.frame.origin.y-self.frame.size.height)];
        self.mTableBaseView.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.8];
        
        UITapGestureRecognizer *bgTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bgTappedAction:)];
        [self.mTableBaseView addGestureRecognizer:bgTap];
        
        
        self.mTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.frame.origin.x, self.frame.size.height+self.frame.origin.y, self.frame.size.width, currentSectionHeight-DROPDOWN_mTableBaseView_BOTTOM_HEIGHT) style:UITableViewStylePlain];
        //只能选择一行
        self.mTableView.allowsMultipleSelection=NO;
        self.mTableView.delegate = self;
        self.mTableView.dataSource = self;
    }
    if (!self.mbTableView) {
        self.mbTableView = [[UITableView alloc] initWithFrame:CGRectMake(sectionWidth+self.frame.origin.x, self.frame.size.height+self.frame.origin.y, self.frame.size.width, currentSectionHeight-DROPDOWN_mTableBaseView_BOTTOM_HEIGHT) style:UITableViewStylePlain];
        self.mbTableView.delegate = self;
        self.mbTableView.dataSource = self;
    }
    
    if ([self.dataSource titleIndexSectionIsBeingWithSection:section]) {
        self.mbTableView=nil;
        sectionWidth=self.frame.size.width;
    }
    
    //修改tableview的frame
    CGRect rect1 = self.mTableView.frame;
    rect1.origin.x = 0;
    rect1.size.width = sectionWidth;
    rect1.size.height = 0;
    
    CGRect rect2 = self.mbTableView.frame;
    rect2.origin.x = sectionWidth;
    rect2.size.width = sectionWidth;
    rect2.size.height = 0;
    
    
    [self.mSuperView addSubview:self.mTableBaseView];
    [self.mSuperView addSubview:self.mTableView];
    [self.mSuperView addSubview:self.mbTableView];
    
    //动画设置位置
    rect1 .size.height = currentSectionHeight-DROPDOWN_mTableBaseView_BOTTOM_HEIGHT;
    rect2.size.height=currentSectionHeight-DROPDOWN_mTableBaseView_BOTTOM_HEIGHT;
    [UIView animateWithDuration:0.3 animations:^{
        self.mTableBaseView.alpha = 0.2;
        self.mTableView.alpha = 0.2;
        self.mbTableView.alpha = 0.2;
        
        self.mTableBaseView.alpha = 1.0;
        self.mTableView.alpha = 1.0;
        self.mbTableView.alpha=1.0;
        self.mTableView.frame = rect1;
        self.mbTableView.frame= rect2;
        
    }];
    
    [self.mTableView reloadData];
    [self.mbTableView reloadData];
}

- (void)setTitle:(NSString *)title inSection:(NSInteger) section
{
    UIButton *btn = (id)[self viewWithTag:SECTION_BTN_TAG_BEGIN +section];
    [btn setTitle:title forState:UIControlStateNormal];
}

- (BOOL)isShow
{
    if (currentExtendSection == -1) {
        return NO;
    }
    return YES;
}
-  (void)hideExtendedChooseView
{
    if (currentExtendSection != -1) {
        currentExtendSection = -1;
        
        currentSelectTitleIndex=0;
        currentSelectIndex=0;
        
        CGRect rect1 = self.mTableView.frame;
        CGRect rect2 = self.mbTableView.frame;
        
        rect1.size.height = 0;
        rect2.size.height = 0;
        
        [UIView animateWithDuration:0.3 animations:^{
            self.mTableBaseView.alpha = 1.0f;
            self.mTableView.alpha = 1.0f;
            self.mbTableView.alpha = 1.0f;
            
            self.mTableBaseView.alpha = 0.2f;
            self.mTableView.alpha = 0.2f;
            self.mbTableView.alpha = 0.2f;
            
            self.mTableView.frame = rect1;
            self.mbTableView.frame=rect2;
            
        }completion:^(BOOL finished) {
            [self.mTableView removeFromSuperview];
            [self.mbTableView removeFromSuperview];
            [self.mTableBaseView removeFromSuperview];
        }];
    }
}


//触表格父视图后隐藏表格
-(void)bgTappedAction:(UITapGestureRecognizer *)tap
{
    UIImageView *currentIV = (UIImageView *)[self viewWithTag:(SECTION_IV_TAG_BEGIN + currentExtendSection)];
    [UIView animateWithDuration:0.3 animations:^{
        currentIV.transform = CGAffineTransformRotate(currentIV.transform, DEGREES_TO_RADIANS(180));
    }];
    [self hideExtendedChooseView];
}
#pragma mark -- UITableView Delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return DROPDOWN_TABLECELL_HEIGHT;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView==self.mTableView) {
        currentSelectIndex=indexPath.row;
        [self.mbTableView reloadData];
        //判断改分组有不有二级列表
        BOOL isIndexList=[self.dataSource titleIndexSectionIsBeingWithSection:currentSelectIndex];
        if (!isIndexList) {
            sectionBtnTitle=[self.dataSource titleInSection:currentExtendSection index:currentSelectIndex];
        }
    }else if(tableView==self.mbTableView)
    {
        currentSelectTitleIndex=indexPath.row;
        NSString *selectString=[self.dataSource titleInSection:currentExtendSection index:currentSelectIndex titleIndex:currentSelectTitleIndex];
        sectionBtnTitle=[sectionBtnTitle stringByAppendingString:selectString];
        //[self hideExtendedChooseView];
    }
    
    UIButton *currentSectionBtn = (UIButton *)[self viewWithTag:SECTION_BTN_TAG_BEGIN + currentExtendSection];
    [currentSectionBtn setTitle:sectionBtnTitle forState:UIControlStateNormal];
    //    if ([self.dropDownDelegate respondsToSelector:@selector(chooseAtSection:index:titleIndex:)]) {
    //
    //        [self.dropDownDelegate chooseAtSection:currentExtendSection index:currentSelectIndex titleIndex:currentSelectTitleIndex];
    //
    //    }
}

#pragma mark -- UITableView DataSource


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView==self.mTableView) {
        return [self.dataSource numberOfRowsInSection:currentExtendSection];
    }else
    {
        return [self.dataSource numberOfRowsInSection:currentExtendSection index:currentSelectIndex];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellIdentifier = @"cellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle=UITableViewCellSelectionStyleGray;
    }
    cell.backgroundColor=[[UIColor whiteColor]  colorWithAlphaComponent:0.5];
    
    if (tableView==self.mTableView) {
        cell.textLabel.text = [self.dataSource titleInSection:currentExtendSection index:indexPath.row];
        
        UIImageView *ImageBg=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width/2.0,DROPDOWN_TABLECELL_HEIGHT)];
        ImageBg.image=[UIImage imageNamed:@"indexBg"];
        cell.backgroundView=ImageBg;
    }else
    {
        cell.textLabel.text=[self.dataSource titleInSection:currentExtendSection index:currentSelectIndex titleIndex:indexPath.row];
        
        UIImageView *ImageBg=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width/2.0,DROPDOWN_TABLECELL_HEIGHT)];
        ImageBg.image=[UIImage imageNamed:@"titleIndexBg"];
        cell.backgroundView=ImageBg;
    }
    
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    return cell;
}


@end
